package com.gree.changying.server.bean;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

/**
 * Create by 游德禄 on 2019-9-16
 * Intent 传值用的
 * 使用方法
 * IntentKV.key(key).setValue(value);
 */
public class IntentKV {
    private String key;
    private Object value;
    private Integer flag;

    public Integer getFlag() {
        return flag;
    }

    public IntentKV addFlag(Integer flag) {
        this.flag = flag;
        return this;
    }

    public static String defaultKey = "key";

    public String getKey() {
        return key;
    }

    public IntentKV setKey(String key) {
        this.key = key;
        return this;
    }

    public Object getValue() {
        return value;
    }

    /**
     * 只接受String,float,int
     * 其他的直接转JSON字符串
     * @param value
     */
    public IntentKV setValue(Object value) {
        this.value = value;
        return this;
    }
    public static IntentKV key(String key){
        return new IntentKV().setKey(key);
    }
    public static IntentKV put(String key,Object value){
        return new IntentKV().setKey(key).setValue(value);
    }

    public static IntentKV flag(int flag){
        return new IntentKV().addFlag(flag);
    }
    /**
     * 默认
     * key
     * 使用方法 IntentKV.set(value)
     * @param value
     * @return
     */
    public static IntentKV set(Object value){
        return new IntentKV().setKey(defaultKey).setValue(value);
    }

    /**
     * 在新页面获取传过来的值
     * String value = IntentKV.get(this);
     * @param activity
     * @param <T>
     * @return
     */
    public static <T>T get(Activity activity){
        return get(activity,null);
    }
    public static <T>T get(Activity activity, String k){
        Intent intent = activity.getIntent();
        Bundle b = intent.getExtras();
        if(b==null){
            return  null;
        }
        if(k==null){
            k = defaultKey;
        }
        for(String key:b.keySet()){
            if(key.equals(k)){
                Object obj = b.get(key);
                if(obj!=null) {
                    return (T) b.get(key);
                }else{
                    return null;
                }
            }
        }
        return null;
    }
}
